package com.hzxy.yiyid.web.module.service.impl;

import com.csvreader.CsvReader;
import com.hzxy.yiyid.web.common.base.BaseResult;
import com.hzxy.yiyid.web.common.constants.YiyidConstants;
import com.hzxy.yiyid.web.common.error.ErrorCodeEnum;
import com.hzxy.yiyid.web.module.repository.*;
import com.hzxy.yiyid.web.module.repository.entity.*;
import com.hzxy.yiyid.web.module.service.DataManageService;
import com.hzxy.yiyid.web.tool.ExcelTool;
import com.hzxy.yiyid.web.tool.baidu.BaiduAI;
import com.hzxy.yiyid.web.tool.baidu.BaiduInfoConverter;
import com.hzxy.yiyid.web.tool.baidu.result.AddressResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @ClassName DataManageServiceImpl
 * @Description 数据处理
 * @Author RAICOM2023
 * @Date 2023/3/6 10:05
 * @Version 1.0
 **/
@Service
@Transactional
public class DataManageServiceImpl implements DataManageService {

    private static final Logger logger = LoggerFactory.getLogger(DataManageServiceImpl.class);

    @Resource
    private DoctorPenaltyDoRepository doctorPenaltyDoRepository;

    @Resource
    private AssignOrganizationDoRepository assignOrganizationDoRepository;

    @Resource
    private SubstandardDrugDoRepository substandardDrugDoRepository;

    @Resource
    private FeverClinicDoRepository feverClinicDoRepository;

    @Resource
    private DiseaseDoRepository diseaseDoRepository;

    @Resource
    private MedicareDrugDoRepository medicareDrugDoRepository;

    @Resource
    private MedicineDoRepository medicineDoRepository;

    @Resource
    private SymptomDoRepository symptomDoRepository;

    private static Map<Character,String> DOCTOR_PENALTY_INFO_TEMPLATE = null;
    static{
        DOCTOR_PENALTY_INFO_TEMPLATE = new HashMap<Character, String>();
        DOCTOR_PENALTY_INFO_TEMPLATE.put('A', "处罚日期");
        DOCTOR_PENALTY_INFO_TEMPLATE.put('B', "处罚种类");
        DOCTOR_PENALTY_INFO_TEMPLATE.put('C', "结案情况");
        DOCTOR_PENALTY_INFO_TEMPLATE.put('D', "处罚机关");
        DOCTOR_PENALTY_INFO_TEMPLATE.put('E', "唯一主键");
        DOCTOR_PENALTY_INFO_TEMPLATE.put('F', "处罚对象");
        DOCTOR_PENALTY_INFO_TEMPLATE.put('G', "处罚决定");
        DOCTOR_PENALTY_INFO_TEMPLATE.put('H', "处罚决定书文号");
        DOCTOR_PENALTY_INFO_TEMPLATE.put('I', "处罚事由");
    }

    private static Map<Character,String> DOCTOR_BLACK_INFO_TEMPLATE = null;
    static{
        DOCTOR_BLACK_INFO_TEMPLATE = new HashMap<Character, String>();
        DOCTOR_BLACK_INFO_TEMPLATE.put('A', "处罚决定书文号");
        DOCTOR_BLACK_INFO_TEMPLATE.put('B', "结案情况");
        DOCTOR_BLACK_INFO_TEMPLATE.put('C', "处罚机关");
        DOCTOR_BLACK_INFO_TEMPLATE.put('D', "处罚日期");
        DOCTOR_BLACK_INFO_TEMPLATE.put('E', "处罚种类");
        DOCTOR_BLACK_INFO_TEMPLATE.put('F', "处罚对象");
        DOCTOR_BLACK_INFO_TEMPLATE.put('G', "处罚决定");
        DOCTOR_BLACK_INFO_TEMPLATE.put('H', "处罚事由");
        DOCTOR_BLACK_INFO_TEMPLATE.put('I', "唯一主键");
    }

    private static Map<Character,String> DD_YL_TEMPLATE = null;
    static{
        DD_YL_TEMPLATE = new HashMap<Character, String>();
        DD_YL_TEMPLATE.put('A', "服务人群");
        DD_YL_TEMPLATE.put('B', "定点医疗机构名称");
        DD_YL_TEMPLATE.put('C', "地址");
        DD_YL_TEMPLATE.put('D', "等级");
        DD_YL_TEMPLATE.put('E', "定点类别");
        DD_YL_TEMPLATE.put('F', "机构编码");
    }

    private static Map<Character,String> DD_YY_TEMPLATE = null;
    static{
        DD_YY_TEMPLATE = new HashMap<Character, String>();
        DD_YY_TEMPLATE.put('A', "服务人群");
        DD_YY_TEMPLATE.put('B', "地址");
        DD_YY_TEMPLATE.put('C', "定点类别");
        DD_YY_TEMPLATE.put('D', "定点医药机构名称");
    }

    private static Map<Character,String> SUBSTANDARD_DRUG_TEMPLATE = null;
    static{
        SUBSTANDARD_DRUG_TEMPLATE = new HashMap<Character, String>();
        SUBSTANDARD_DRUG_TEMPLATE.put('A', "抽查检查时间");
        SUBSTANDARD_DRUG_TEMPLATE.put('B', "批号");
        SUBSTANDARD_DRUG_TEMPLATE.put('C', "主体类别");
        SUBSTANDARD_DRUG_TEMPLATE.put('D', "标示生产单位");
        SUBSTANDARD_DRUG_TEMPLATE.put('E', "抽查检查项目名称");
        SUBSTANDARD_DRUG_TEMPLATE.put('F', "药品名称");
        SUBSTANDARD_DRUG_TEMPLATE.put('G', "规格");
        SUBSTANDARD_DRUG_TEMPLATE.put('H', "抽查检查机构统一社会信用代码");
        SUBSTANDARD_DRUG_TEMPLATE.put('I', "有效期");
        SUBSTANDARD_DRUG_TEMPLATE.put('J', "不合格项目");
        SUBSTANDARD_DRUG_TEMPLATE.put('K', "检验机构");
        SUBSTANDARD_DRUG_TEMPLATE.put('L', "检验依据");
        SUBSTANDARD_DRUG_TEMPLATE.put('M', "备注");
        SUBSTANDARD_DRUG_TEMPLATE.put('N', "抽查检查类别");
        SUBSTANDARD_DRUG_TEMPLATE.put('O', "编号");
        SUBSTANDARD_DRUG_TEMPLATE.put('P', "检品来源");
        SUBSTANDARD_DRUG_TEMPLATE.put('Q', "检验结果");
        SUBSTANDARD_DRUG_TEMPLATE.put('R', "统一社会信用代码");
    }

    private static Map<Character,String> FEVER_CLINIC_TEMPLATE = null;
    static{
        FEVER_CLINIC_TEMPLATE = new HashMap<Character, String>();
        FEVER_CLINIC_TEMPLATE.put('A', "机构名称");
        FEVER_CLINIC_TEMPLATE.put('B', "区县代码");
        FEVER_CLINIC_TEMPLATE.put('C', "地址");
        FEVER_CLINIC_TEMPLATE.put('D', "地市代码");
        FEVER_CLINIC_TEMPLATE.put('E', "区县名称");
        FEVER_CLINIC_TEMPLATE.put('F', "地市名称");
        FEVER_CLINIC_TEMPLATE.put('G', "日期");
    }
    private static Map<Character,String> MEDICARE_DRUG_TEMPLATE = null;
    static{
        MEDICARE_DRUG_TEMPLATE = new HashMap<Character, String>();
        MEDICARE_DRUG_TEMPLATE.put('A', "规格");
        MEDICARE_DRUG_TEMPLATE.put('B', "商品名");
        MEDICARE_DRUG_TEMPLATE.put('C', "包装材质");
        MEDICARE_DRUG_TEMPLATE.put('D', "单位");
        MEDICARE_DRUG_TEMPLATE.put('E', "主键");
        MEDICARE_DRUG_TEMPLATE.put('F', "转换比");
        MEDICARE_DRUG_TEMPLATE.put('G', "备注");
        MEDICARE_DRUG_TEMPLATE.put('H', "招标药品通用名");
        MEDICARE_DRUG_TEMPLATE.put('I', "生产企业");
        MEDICARE_DRUG_TEMPLATE.put('J', "剂型");
    }

    /*
     * @Author RAICOM2023
     * @Description //上传数据
     * @Date 10:04 2023/3/6
     * @Param [dataType, file]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    @Override
    public BaseResult<?> uploadData(Integer dataType, MultipartFile file) throws Exception {
        if(7==dataType){
            return readDiseaseData(file);
        }else if(8==dataType){
            return readMedicineData(file);
        }else if(9==dataType){
            return readSymptomData(file);
        }
        Map<Character,String> template = selectTemplate(dataType);
        if(null==template){
            return BaseResult.error(ErrorCodeEnum.DATA_TYPE_ERROR.getErrorCode(),ErrorCodeEnum.DATA_TYPE_ERROR.getMsg());
        }
        List result = ExcelTool.importExcelFile(file, template);
        String resultMsg = (String) result.get(0);
        if(ExcelTool.RESULT_MSG_SUCCESS.equals(resultMsg)){
            List<List<String>> dataList = (List<List<String>>) result.get(1);
            if(dataList!=null && dataList.size()!=0){
                switch (dataType){
                    case 0:
                        return importDoctorPenaltyInfo(dataList);
                    case 1:
                        return importDoctorBlackInfo(dataList);
                    case 2:
                        return importDdyl(dataList);
                    case 3:
                        return importDdyy(dataList);
                    case 4:
                        return importFeverClinicInfo(dataList);
                    case 5:
                        return importSubstandardDrugInfo(dataList);
                    case 6:
                        return importMedicareDrugInfo(dataList);
                }
            }
            return BaseResult.error(ErrorCodeEnum.DATA_IMPORT_ERROR.getErrorCode(),ErrorCodeEnum.DATA_IMPORT_ERROR.getMsg());
        }else{
            logger.error("数据导入失败信息："+resultMsg);
            return BaseResult.error(ErrorCodeEnum.DATA_IMPORT_ERROR.getErrorCode(),ErrorCodeEnum.DATA_IMPORT_ERROR.getMsg());
        }
    }

    /*
     * @Author RAICOM2023
     * @Description //选择excel模板
     * @Date 10:25 2023/3/6
     * @Param [dataType]
     * @return java.util.Map<java.lang.Character,java.lang.String>
     **/
    private Map<Character,String> selectTemplate(Integer dataType){
        switch (dataType){
            case 0:
                return DOCTOR_PENALTY_INFO_TEMPLATE;
            case 1:
                return DOCTOR_BLACK_INFO_TEMPLATE;
            case 2:
                return DD_YL_TEMPLATE;
            case 3:
                return DD_YY_TEMPLATE;
            case 4:
                return FEVER_CLINIC_TEMPLATE;
            case 5:
                return SUBSTANDARD_DRUG_TEMPLATE;
            case 6:
                return MEDICARE_DRUG_TEMPLATE;
        }
        return null;
    }

    /*
     * @Author RAICOM2023
     * @Description //导入医师行政处罚信息
     * @Date 10:42 2023/3/6
     * @Param [dataList]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    private BaseResult<?> importDoctorPenaltyInfo(List<List<String>> dataList){
        List<DoctorPenaltyDo> saveList = new ArrayList<DoctorPenaltyDo>();
        for(List<String> data : dataList){
            boolean flag = true;
            for(String s : data){
                if(!"null".equals(s)){
                    flag  = false;
                }
            }
            if(flag){
                continue;
            }
            data = convertData(data);
            DoctorPenaltyDo doctorPenaltyDo = new DoctorPenaltyDo(data.get(5),data.get(7),data.get(1),data.get(8)
                    ,data.get(6),data.get(0),data.get(2),data.get(3),data.get(4));
            saveList.add(doctorPenaltyDo);
        }
        if(CollectionUtils.isNotEmpty(saveList)){
            doctorPenaltyDoRepository.saveAll(saveList);
            doctorPenaltyDoRepository.flush();
        }
        return BaseResult.success(YiyidConstants.SUCCESS_STRING);
    }

    /*
     * @Author RAICOM2023
     * @Description //导入非法行医黑名单信息
     * @Date 10:42 2023/3/6
     * @Param [dataList]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    private BaseResult<?> importDoctorBlackInfo(List<List<String>> dataList){
        List<DoctorPenaltyDo> saveList = new ArrayList<DoctorPenaltyDo>();
        for(List<String> data : dataList){
            boolean flag = true;
            for(String s : data){
                if(!"null".equals(s)){
                    flag  = false;
                }
            }
            if(flag){
                continue;
            }
            data = convertData(data);
            DoctorPenaltyDo doctorPenaltyDo = new DoctorPenaltyDo(data.get(5),data.get(0),data.get(4),data.get(7)
                    ,data.get(6),data.get(3),data.get(1),data.get(2),data.get(8));
            saveList.add(doctorPenaltyDo);
        }
        if(CollectionUtils.isNotEmpty(saveList)){
            doctorPenaltyDoRepository.saveAll(saveList);
            doctorPenaltyDoRepository.flush();
        }
        return BaseResult.success(YiyidConstants.SUCCESS_STRING);
    }

    /*
     * @Author RAICOM2023
     * @Description //导入定点医疗机构信息
     * @Date 15:34 2023/3/6
     * @Param [dataList]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    private BaseResult<?> importDdyl(List<List<String>> dataList){
        List<AssignOrganizationDo> saveList = new ArrayList<AssignOrganizationDo>();
        for(List<String> data : dataList){
            boolean flag = true;
            for(String s : data){
                if(!"null".equals(s)){
                    flag  = false;
                }
            }
            if(flag){
                continue;
            }
            data = convertData(data);
            String addressInfo = data.get(2);
            AddressResult addressResult = null;
            try{
                addressResult = BaiduInfoConverter.convertAddressResult(BaiduAI.NLP_ADDRESS(addressInfo));
            }catch(Exception e){
                logger.error("地址转换出错,"+data.get(1)+","+data.get(2),e);
            }
            AssignOrganizationDo assignOrganizationDo = new AssignOrganizationDo(data.get(0),data.get(1),data.get(2)
                    ,data.get(3),data.get(4),data.get(5),0,addressResult.getProvince(),addressResult.getProvinceCode()
                    ,addressResult.getCity(),addressResult.getCityCode(),addressResult.getCounty()
                    ,addressResult.getCountyCode(),addressResult.getTown(),addressResult.getTownCode()
                    ,addressResult.getDetail(),addressResult.getLat(),addressResult.getLng());
            saveList.add(assignOrganizationDo);
        }
        if(CollectionUtils.isNotEmpty(saveList)){
            assignOrganizationDoRepository.saveAll(saveList);
            assignOrganizationDoRepository.flush();
        }
        return BaseResult.success(YiyidConstants.SUCCESS_STRING);
    }

    /*
     * @Author RAICOM2023
     * @Description //导入定点医药机构信息
     * @Date 16:14 2023/3/6
     * @Param [dataList]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    private BaseResult<?> importDdyy(List<List<String>> dataList){
        List<AssignOrganizationDo> saveList = new ArrayList<AssignOrganizationDo>();
        for(List<String> data : dataList){
            boolean flag = true;
            for(String s : data){
                if(!"null".equals(s)){
                    flag  = false;
                }
            }
            if(flag){
                continue;
            }
            data = convertData(data);
            String addressInfo = data.get(1);
            AddressResult addressResult = null;
            try{
                addressResult = BaiduInfoConverter.convertAddressResult(BaiduAI.NLP_ADDRESS(addressInfo));
            }catch(Exception e){
                logger.error("地址转换出错,"+data.get(1),e);
            }
            AssignOrganizationDo assignOrganizationDo = new AssignOrganizationDo(data.get(0),data.get(3),data.get(1)
                    ,null,data.get(2),null,1,addressResult.getProvince(),addressResult.getProvinceCode()
                    ,addressResult.getCity(),addressResult.getCityCode(),addressResult.getCounty()
                    ,addressResult.getCountyCode(),addressResult.getTown(),addressResult.getTownCode()
                    ,addressResult.getDetail(),addressResult.getLat(),addressResult.getLng());
            saveList.add(assignOrganizationDo);
        }
        if(CollectionUtils.isNotEmpty(saveList)){
            assignOrganizationDoRepository.saveAll(saveList);
            assignOrganizationDoRepository.flush();
        }
        return BaseResult.success(YiyidConstants.SUCCESS_STRING);
    }

    /*
     * @Author RAICOM2023
     * @Description //导入不合格药品信息
     * @Date 16:55 2023/3/6
     * @Param [dataList]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    private BaseResult<?> importSubstandardDrugInfo(List<List<String>> dataList){
        List<SubstandardDrugDo> saveList = new ArrayList<SubstandardDrugDo>();
        for(List<String> data : dataList){
            boolean flag = true;
            for(String s : data){
                if(!"null".equals(s)){
                    flag  = false;
                }
            }
            if(flag){
                continue;
            }
            data = convertData(data);
            SubstandardDrugDo substandardDrugDo = new SubstandardDrugDo(data.get(0),data.get(1),data.get(2),data.get(3)
                    ,data.get(4),data.get(5),data.get(6),data.get(7),data.get(8),data.get(9),data.get(10),data.get(11)
                    ,data.get(12),data.get(13),data.get(14),data.get(15),data.get(16),data.get(17));
            saveList.add(substandardDrugDo);
        }
        if(CollectionUtils.isNotEmpty(saveList)){
            substandardDrugDoRepository.saveAll(saveList);
            substandardDrugDoRepository.flush();
        }
        return BaseResult.success(YiyidConstants.SUCCESS_STRING);
    }

    /*
     * @Author RAICOM2023
     * @Description //导入发热门诊信息
     * @Date 16:57 2023/3/6
     * @Param [dataList]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    private BaseResult<?> importFeverClinicInfo(List<List<String>> dataList){
        List<FeverClinicDo> saveList = new ArrayList<FeverClinicDo>();
        for(List<String> data : dataList){
            boolean flag = true;
            for(String s : data){
                if(!"null".equals(s)){
                    flag  = false;
                }
            }
            if(flag){
                continue;
            }
            data = convertData(data);
            String addressInfo = data.get(4);
            AddressResult addressResult = null;
            try{
                addressResult = BaiduInfoConverter.convertAddressResult(BaiduAI.NLP_ADDRESS(addressInfo));
            }catch(Exception e){
                logger.error("地址转换出错,"+data.get(0)+","+data.get(4),e);
            }
            FeverClinicDo feverClinicDo = new FeverClinicDo(data.get(0),data.get(2),data.get(4),addressResult.getProvince()
                    ,addressResult.getProvinceCode(),addressResult.getCity(),addressResult.getCityCode()
                    ,addressResult.getCounty(),addressResult.getCountyCode(),addressResult.getTown()
                    ,addressResult.getTownCode(),addressResult.getDetail(),addressResult.getLat(),addressResult.getLng());
            saveList.add(feverClinicDo);
        }
        if(CollectionUtils.isNotEmpty(saveList)){
            feverClinicDoRepository.saveAll(saveList);
            feverClinicDoRepository.flush();
        }
        return BaseResult.success(YiyidConstants.SUCCESS_STRING);
    }

    /*
     * @Author RAICOM2023
     * @Description //导入医保药品信息
     * @Date 18:53 2023/3/6
     * @Param [dataList]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    private BaseResult<?> importMedicareDrugInfo(List<List<String>> dataList){
        List<MedicareDrugDo> saveList = new ArrayList<MedicareDrugDo>();
        Set<String> drugNameSet = new HashSet<>();
        for(List<String> data : dataList){
            boolean flag = true;
            for(String s : data){
                if(!"null".equals(s)){
                    flag  = false;
                }
            }
            if(flag){
                continue;
            }
            data = convertData(data);
            if(StringUtils.isBlank(data.get(7)) || data.get(7).equals("无")){
                continue;
            }
            if(drugNameSet.contains(data.get(7)) || CollectionUtils.isNotEmpty(medicareDrugDoRepository.findByTym(data.get(7)))){
                continue;
            }
            String tym = splitTym(data.get(7));
            drugNameSet.add(tym);
            String spm = data.get(1);
            if(StringUtils.isNotBlank(spm) && spm.equals("无")){
                spm = null;
            }
            MedicareDrugDo medicareDrugDo = new MedicareDrugDo(data.get(0),spm,data.get(2),data.get(3),data.get(4),data.get(5)
                    ,data.get(6),tym,data.get(8),data.get(9));
            saveList.add(medicareDrugDo);
        }
        if(CollectionUtils.isNotEmpty(saveList)){
            medicareDrugDoRepository.saveAll(saveList);
            medicareDrugDoRepository.flush();
        }
        return BaseResult.success(YiyidConstants.SUCCESS_STRING);
    }

    /*
     * @Author RAICOM2023
     * @Description //TODO
     * @Date 11:21 2023/3/6
     * @Param [data]
     * @return List
     **/
    private List<String> convertData(List<String> data){
        List<String> newList = new ArrayList<>();
        for(String s : data){
            if(StringUtils.isBlank(s) || s.trim().equals("null")){
                newList.add(null);
            }else{
                newList.add(s.trim());
            }
        }
        return newList;
    }

    /*
     * @Author RAICOM2023
     * @Description //导入疾病数据
     * @Date 19:18 2023/3/6
     * @Param [file]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    @Override
    public BaseResult<?> readDiseaseData(MultipartFile file) throws Exception{
        List<DiseaseDo> list = new ArrayList<DiseaseDo>();
        // 创建CSV读对象
        File file2 = new File("data/disease.csv");
        InputStreamReader isr=new InputStreamReader(new FileInputStream(file2),"UTF-8");
        //InputStreamReader isr=new InputStreamReader(file.getInputStream());
        CsvReader csvReader = new CsvReader(isr);
        csvReader.readHeaders();
        while (csvReader.readRecord()){
            DiseaseDo diseaseDo= new DiseaseDo();
            diseaseDo.setDiseaseNumber(csvReader.get("疾病编号").trim());
            diseaseDo.setDiseaseName(csvReader.get("疾病名称").trim());
            String m1 = csvReader.get("用药方案1").trim();
            if(StringUtils.isNotBlank(m1)){
                diseaseDo.setMedicationPlanOne(splitData2(m1.trim()));
            }
            String mn1 = csvReader.get("用药方案1准字号").trim();
            if(StringUtils.isNotBlank(mn1)){
                diseaseDo.setMedicationPlanOneGyzz(splitData2(mn1.trim()));
            }
            String m2 = csvReader.get("用药方案2").trim();
            if(StringUtils.isNotBlank(m1)){
                diseaseDo.setMedicationPlanTwo(splitData2(m2.trim()));
            }
            String mn2 = csvReader.get("用药方案2准字号").trim();
            if(StringUtils.isNotBlank(m1)){
                diseaseDo.setMedicationPlanTwoGyzz(splitData2(mn2.trim()));
            }
            list.add(diseaseDo);
        }
        diseaseDoRepository.saveAll(list);
        diseaseDoRepository.flush();
        return BaseResult.success(YiyidConstants.SUCCESS_STRING);
    }

    /*
     * @Author RAICOM2023
     * @Description //导入用药数据
     * @Date 19:28 2023/3/6
     * @Param [file]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    @Override
    public BaseResult<?> readMedicineData(MultipartFile file) throws Exception{
        List<MedicineDo> list = new ArrayList<MedicineDo>();
        // 创建CSV读对象
        File file2 = new File("data/medicine.csv");
        InputStreamReader isr=new InputStreamReader(new FileInputStream(file2),"UTF-8");
        //InputStreamReader isr=new InputStreamReader(file.getInputStream());
        CsvReader csvReader = new CsvReader(isr);
        csvReader.readHeaders();
        while (csvReader.readRecord()){
            MedicineDo medicineDo= new MedicineDo();
            medicineDo.setGyzz(csvReader.get("国药准字").trim());
            medicineDo.setChineseName(csvReader.get("药品名称").trim());
            medicineDo.setEnglishName(csvReader.get("英文名称").trim());
            medicineDo.setPinYin(csvReader.get("汉语拼音").trim());
            medicineDo.setIsRx(csvReader.get("是否处方药").trim());
            medicineDo.setCompany(csvReader.get("企业名称").trim());
            medicineDo.setFunction(csvReader.get("主治功能").trim());
            medicineDo.setIngredients(csvReader.get("药品成分").trim());
            medicineDo.setAdrs(csvReader.get("不良反应").trim());
            medicineDo.setInteraction(csvReader.get("药物相互作用").trim());
            medicineDo.setStandard(csvReader.get("执行标准").trim());
            medicineDo.setTaboo(csvReader.get("禁忌").trim());
            medicineDo.setCharacter(csvReader.get("性状").trim());
            medicineDo.setSpecifications(csvReader.get("规格").trim());
            medicineDo.setUsage(csvReader.get("用法用量").trim());
            medicineDo.setAttention(csvReader.get("注意事项").trim());
            list.add(medicineDo);
        }
        medicineDoRepository.saveAll(list);
        medicineDoRepository.flush();
        return BaseResult.success(YiyidConstants.SUCCESS_STRING);
    }

    /*
     * @Author RAICOM2023
     * @Description //导入症状数据
     * @Date 19:38 2023/3/6
     * @Param [file]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    @Override
    public  BaseResult<?> readSymptomData(MultipartFile file) throws Exception{
        List<SymptomDo> list = new ArrayList<SymptomDo>();
        // 创建CSV读对象
        File file2 = new File("data/symptom.csv");
        InputStreamReader isr=new InputStreamReader(new FileInputStream(file2),"UTF-8");
        //InputStreamReader isr=new InputStreamReader(file.getInputStream());
        CsvReader csvReader = new CsvReader(isr);
        csvReader.readHeaders();
        int i = 0;
        Map<String, Set<String>> symptomAndDisNumberMap = new HashMap<>();
        Map<String, Set<String>> symptomAndDisNameMap = new HashMap<>();
        while (csvReader.readRecord()){
            String symptom = csvReader.get("症状关键字").trim();
            Set<String> disNames  = splitData(csvReader.get("疾病").trim());
            Set<String> disNumbers = splitData(csvReader.get("对应疾病编号").trim());
            Set<String> disNumbersTemp = new HashSet<>();
            for(String str : disNumbers){
                str = Integer.parseInt(str)+"";
                disNumbersTemp.add(str);
            }
            disNumbers = disNumbersTemp;
            if(symptomAndDisNumberMap.containsKey(symptom)){
                symptomAndDisNumberMap.get(symptom).addAll(disNumbers);
            }else{
                symptomAndDisNumberMap.put(symptom,disNumbers);
            }
            if(symptomAndDisNameMap.containsKey(symptom)){
                symptomAndDisNameMap.get(symptom).addAll(disNames);
            }else{
                symptomAndDisNameMap.put(symptom,disNames);
            }
        }
        for(Map.Entry<String,Set<String>> entry : symptomAndDisNumberMap.entrySet()){
            SymptomDo symptomDo= new SymptomDo();
            i++;
            StringBuilder sb = new StringBuilder();
            sb.append(i);
            while(sb.length()<4){
                sb.insert(0,"0");
            }
            symptomDo.setSymptomNumber(1+sb.toString());
            symptomDo.setSymptomName(entry.getKey());
            List<String> names = new ArrayList<>();
            names.addAll(symptomAndDisNameMap.get(entry.getKey()));
            List<String> numbers = new ArrayList<>();
            numbers.addAll(entry.getValue());
            symptomDo.setDiseaseNumber(numbers);
            symptomDo.setDiseaseName(names);
            list.add(symptomDo);
        }
        symptomDoRepository.saveAll(list);
        symptomDoRepository.flush();
        return BaseResult.success(YiyidConstants.SUCCESS_STRING);
    }

    /*
     * @Author RAICOM2023
     * @Description //转换医保药品通用名
     * @Date 21:06 2023/3/6
     * @Param []
     * @return java.lang.String
     **/
    private String splitTym(String tym){
        return tym.split("\n")[0].split("\\(")[0].split("（")[0];
    }

    /*
     * @Author RAICOM2023
     * @Description //TODO
     * @Date 19:16 2023/3/6
     * @Param [data]
     * @return java.util.Set<java.lang.String>
     **/
    private Set<String> splitData(String data){
        Set<String> set = new HashSet<>();
        if(StringUtils.isNotBlank(data)){
            for(String singleData : data.split("\\+|;|、|,|；|，")){
                if(StringUtils.isNotBlank(singleData)){
                    set.add(singleData.trim());
                }
            }
        }
        return set;
    }

    /*
     * @Author RAICOM2023
     * @Description //TODO
     * @Date 19:16 2023/3/6
     * @Param [data]
     * @return java.util.List<java.lang.String>
     **/
    private List<String> splitData2(String data){
        List<String> list = new ArrayList<>();
        if(StringUtils.isNotBlank(data)){
            for(String singleData : data.split("\\+|;|、|,|；|，")){
                if(StringUtils.isNotBlank(singleData)){
                    list.add(singleData.trim());
                }
            }
        }
        return list;
    }
}
